from fastapi import APIRouter, Depends
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session

from controller.UserAdminController import UserAdminController
from schema.ParamSchema import UserInfo, UserModPwdInfo, PortMenusInfo
from util.Auth import check_token
from util.DataBaseTools import get_db_session
from util.ErrorCode import ErrorCode
from util.LogHelper import Log

user_admin_router = APIRouter()


@user_admin_router.post("/user/create", summary='创建用户')
def add_user(userInfo: UserInfo, db: Session = Depends(get_db_session), result=Depends(check_token)):
    Log.getlogger().debug(f'recieved request:/user/create')
    if result.get('code') == 0:
        if result.get('data').port_id == 0:
            response = UserAdminController.add_user(userInfo, db)
            return response
        else:
            return {'code': ErrorCode.USERID_HAS_NO_PERMISSION.value, 'message': 'user has no permission'}
    else:
        return result


@user_admin_router.post("/user/login", summary='用户登录')
def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db_session)):
    Log.getlogger().debug(f'recieved request:/user/login')
    response = UserAdminController.login(form_data.username, form_data.password, db)
    return response


@user_admin_router.post("/user/password/mod", summary='用户修改密码')
def mod_password(userModPwdInfo: UserModPwdInfo, db: Session = Depends(get_db_session), result=Depends(check_token)):
    Log.getlogger().debug(f'recieved request:/user/login')
    if result.get('code') == 0:
        user_id = result.get('data').user_id
        hashed_password = result.get('data').password
        response = UserAdminController.mod_password(userModPwdInfo, user_id, hashed_password, db)
        return response
    else:
        return result



